/**
 * Project Name:九色鹿
 * File Name:ByteFormat.java
 * Package Name:com.fxp.project.jiuselu.onekey.utils.bytes
 * Date:2020年04月02日 0:41
 * Copyright (c) 2020, Jason.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.onekey.utils.bytes;

/**
 * ClassName:ByteFormat<br/>
 * Function: 字节格式化<br/>
 * Date:2020年04月02日 0:41<br/>
 *
 * @author Jason.Wang
 * @version 1.0.0.0
 * @see
 * @since JDK1.8
 */
public class ByteFormat {
    private static final char[] HEX = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * bytesToHexString: 将字节数组处理成String<br/>
     *
     * @param bArray
     * @return
     * @author Jason.Wang
     * @createTime 2020/4/2 0:42
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        for (int i = 0; i < bArray.length; ++i) {
            String sTemp = Integer.toHexString(255 & bArray[i]);
            if (sTemp.length() < 2) {
                sb.append(0);
            }
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * hexToBytes: 将处理后的Hex值还原成字节数组<br/>
     *
     * @param str
     * @return
     * @author Jason.Wang
     * @createTime 2020/4/2 0:42
     */
    public static byte[] hexToBytes(String str) {
        if (str == null) {
            return null;
        } else {
            char[] hex = str.toCharArray();
            int length = hex.length / 2;
            byte[] raw = new byte[length];

            for (int i = 0; i < length; ++i) {
                int high = Character.digit(hex[i * 2], 16);
                int low = Character.digit(hex[i * 2 + 1], 16);
                int value = high << 4 | low;
                if (value > 127) {
                    value -= 256;
                }
                raw[i] = (byte) value;
            }
            return raw;
        }
    }
}
